package com.integrationpath.mengine.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.integrationpath.mengine.service.GenericManager;
import com.integrationpath.mengine.model.LinkCategory;
import com.integrationpath.mengine.webapp.action.BaseAction;

import java.util.List;

public class LinkCategoryAction extends BaseAction implements Preparable {
    private GenericManager<LinkCategory, Integer> linkCategoryManager;
    private List linkCategories;
    private LinkCategory linkCategory;
    private Integer  id;

    public void setLinkCategoryManager(GenericManager<LinkCategory, Integer> linkCategoryManager) {
        this.linkCategoryManager = linkCategoryManager;
    }

    public List getLinkCategories() {
        return linkCategories;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String linkCategoryId = getRequest().getParameter("linkCategory.id");
            if (linkCategoryId != null && !linkCategoryId.equals("")) {
                linkCategory = linkCategoryManager.get(new Integer(linkCategoryId));
            }
        }
    }

    public String list() {
        linkCategories = linkCategoryManager.getAll();
        return SUCCESS;
    }

    public void setId(Integer  id) {
        this. id =  id;
    }

    public LinkCategory getLinkCategory() {
        return linkCategory;
    }

    public void setLinkCategory(LinkCategory linkCategory) {
        this.linkCategory = linkCategory;
    }

    public String delete() {
        linkCategoryManager.remove(linkCategory.getId());
        saveMessage(getText("linkCategory.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            linkCategory = linkCategoryManager.get(id);
        } else {
            linkCategory = new LinkCategory();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (new Integer(linkCategory.getId()) == null);

        linkCategoryManager.save(linkCategory);

        String key = (isNew) ? "linkCategory.added" : "linkCategory.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}